package com.quanshu.exchange.ui.gui.message.chat.row;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.chat.ChatCommonUtils;
import com.quanshu.exchange.support.chat.ChatConstant;
import com.quanshu.exchange.support.utils.LogUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.MyApplication;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.DefaultViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.ImageReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.ImageSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.NotifyViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.RedPackageReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.RedPackageSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.TextReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.TextSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VideoCallReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VideoCallSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VideoReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VideoSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceCallReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceCallSendViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceReceiveViewHolder;
import com.quanshu.exchange.ui.gui.message.chat.row.viewholder.VoiceSendViewHolder;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * Created by jye on 2018/1/19.
 */

public class ChatMessageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static enum ITEM_TYPE {
        ITEM_DEFAULT_VIEW,
        ITEM_NOTIFY_VIEW,
        ITEM_TYPE_RECEIVE_IMAGE,
        ITEM_TYPE_RECEIVE_TEXT,
        ITEM_TYPE_SEND_IMAGE,
        ITEM_TYPE_SEND_TEXT,
        ITEM_TYPE_SEND_VOICE,
        ITEM_TYPE_RECEIVE_VOICE,
        ITEM_TYPE_SEND_VIDEO,
        ITEM_TYPE_RECEIVE_VIDEO,
        ITEM_TYPE_SEND_VIDEO_CALL,
        ITEM_TYPE_RECEIVE_VIDEO_CALL,
        ITEM_TYPE_SEND_VOICE_CALL,
        ITEM_TYPE_RECEIVE_VOICE_CALL,
        ITEM_TYPE_SEND_RED_PACKAGE,
        ITEM_TYPE_RECEIVE_RED_PACKAGE
    }

    private final LayoutInflater mLayoutInflater;
    private RecyclerView recyclerView;
    private final Context mContext;
    private EMConversation conversation;
    public List<EMMessage> dataList = new ArrayList<>();
    private String groupOwner;
    private View rootView;

    private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
    private static final int HANDLER_MESSAGE_SELECT_LAST = 1;
    private static final int HANDLER_MESSAGE_SEEK_TO = 2;
    private static final int HANDLER_MESSAGE_LOAD_FINISH = 3;

    // 群主点击回复按钮回调
    private OnChatItemClickListener onChatItemClickListener;

    public void setOnChatItemClickListener(OnChatItemClickListener listener) {
        this.onChatItemClickListener = listener;
    }

    public ChatMessageAdapter(Context context, EMConversation conversation, String groupOwner, RecyclerView recyclerView, View view) {
        mContext = context;
        this.conversation = conversation;
        this.groupOwner = groupOwner;
        this.recyclerView = recyclerView;
        this.rootView = view;
        mLayoutInflater = LayoutInflater.from(context);
    }

    public void refreshList() {
        if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
            return;
        }
        Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
        handler.sendMessage(msg);
    }

    private void loadData() {
        Thread thread = new Thread(() -> {
            dataList.clear();
            List<EMMessage> allMessages = conversation.getAllMessages();
            Iterator<EMMessage> iter = allMessages.iterator();
            while (iter.hasNext()) {
                EMMessage message = iter.next();
                boolean visibility = ChatCommonUtils.getChatMsgVisibility(message, groupOwner,
                        MyApplication.getInstance().getCurrentUser().getMemberid());
                if (!visibility) {
                    iter.remove();
                }
            }
            dataList.addAll(allMessages);
            Message msg = handler.obtainMessage(HANDLER_MESSAGE_LOAD_FINISH);
            handler.sendMessage(msg);
        });
        thread.start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message message) {
            switch (message.what) {
                case HANDLER_MESSAGE_REFRESH_LIST:
                    LogUtil.print("===HANDLER_MESSAGE_REFRESH_LIST====");
                    loadData();
                    break;
                case HANDLER_MESSAGE_SELECT_LAST:
                    int lastPosition = dataList.size() - 1;
                    if (dataList != null && lastPosition > 0) {
                        LogUtil.print("===HANDLER_MESSAGE_SELECT_LAST====" + lastPosition);
                        recyclerView.scrollToPosition(lastPosition);
                        ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, 0);
                    }
                    break;
                case HANDLER_MESSAGE_SEEK_TO:
                    LogUtil.print("===HANDLER_MESSAGE_SEEK_TO====");
                    int position = message.arg1;
                    ((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                    break;
                case HANDLER_MESSAGE_LOAD_FINISH:
                    LogUtil.print("===HANDLER_MESSAGE_LOAD_FINISH====");
                    notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }
    };

    public void refreshToLast() {
        final int TIME_DELAY_REFRESH_SELECT_LAST = 300;
        handler.removeMessages(HANDLER_MESSAGE_REFRESH_LIST);
        handler.removeMessages(HANDLER_MESSAGE_SELECT_LAST);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_REFRESH_LIST, 100);
        handler.sendEmptyMessageDelayed(HANDLER_MESSAGE_SELECT_LAST, TIME_DELAY_REFRESH_SELECT_LAST);
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        // 接收图片消息
        if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_IMAGE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_picture, parent, false);
            return new ImageReceiveViewHolder(mContext, view, dataList);
        }
        // 发送图片消息
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_IMAGE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_picture, parent, false);
            return new ImageSendViewHolder(mContext, view, dataList);
        }
        // 发送文字消息
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_TEXT.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_text, parent, false);
            return new TextSendViewHolder(mContext, view);
        }
        // 发送语音消息
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_VOICE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_voice, parent, false);
            return new VoiceSendViewHolder(mContext, view);
        }
        //  接收语音消息
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_VOICE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_voice, parent, false);
            return new VoiceReceiveViewHolder(mContext, view);
        }
        // 接收文字消息
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_TEXT.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_text, parent, false);
            return new TextReceiveViewHolder(mContext, view);
        }
        // 发起视频通话
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_VIDEO_CALL.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_video_call, parent, false);
            return new VideoCallSendViewHolder(mContext, view);
        }
        // 接收视频通话
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_VIDEO_CALL.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_video_call, parent, false);
            return new VideoCallReceiveViewHolder(mContext, view);
        }
        // 发起语音通话
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_VOICE_CALL.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_voice_call, parent, false);
            return new VideoCallSendViewHolder(mContext, view);
        }
        // 接收语音通话
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_VOICE_CALL.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_voice_call, parent, false);
            return new VideoCallReceiveViewHolder(mContext, view);
        }
        // 发送小视频
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_VIDEO.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_video, parent, false);
            return new VideoSendViewHolder(mContext, view);
        }
        // 接收小视频
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_VIDEO.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_video, parent, false);
            return new VideoReceiveViewHolder(mContext, view);
        }
        // 发送红包
        else if (viewType == ITEM_TYPE.ITEM_TYPE_SEND_RED_PACKAGE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_send_red_package, parent, false);
            return new RedPackageSendViewHolder(mContext, view);
        }
        // 接收红包
        else if (viewType == ITEM_TYPE.ITEM_TYPE_RECEIVE_RED_PACKAGE.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_received_red_package, parent, false);
            return new RedPackageReceiveViewHolder(mContext, view);
        }
        // 通知类型
        else if (viewType == ITEM_TYPE.ITEM_NOTIFY_VIEW.ordinal()) {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_notify_text, parent, false);
            return new NotifyViewHolder(mContext, view);
        }
        // 默认未知消息类型
        else {
            View view = mLayoutInflater.inflate(R.layout.item_chat_row_default_text, parent, false);
            return new DefaultViewHolder(mContext, view);
        }
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        EMMessage data = dataList.get(position);
        EMMessage preMessage;
        if (position == 0) {
            preMessage = null;
        } else {
            preMessage = dataList.get(position - 1);
        }
        if (holder instanceof ImageReceiveViewHolder) {
            ((ImageReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof TextReceiveViewHolder) {
            ((TextReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof ImageSendViewHolder) {
            ((ImageSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof TextSendViewHolder) {
            ((TextSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VoiceReceiveViewHolder) {
            ((VoiceReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VoiceSendViewHolder) {
            ((VoiceSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VideoCallSendViewHolder) {
            ((VideoCallSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VideoCallReceiveViewHolder) {
            ((VideoCallReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VoiceCallSendViewHolder) {
            ((VoiceCallSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VoiceCallReceiveViewHolder) {
            ((VoiceCallReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VideoSendViewHolder) {
            ((VideoSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof VideoReceiveViewHolder) {
            ((VideoReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof RedPackageReceiveViewHolder) {
            ((RedPackageReceiveViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof RedPackageSendViewHolder) {
            ((RedPackageSendViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else if (holder instanceof NotifyViewHolder) {
            ((NotifyViewHolder) holder).setViewInfo(data, preMessage, groupOwner);

        } else {
            ((DefaultViewHolder) holder).setViewInfo(data, preMessage, groupOwner);
        }
        // 点击回复按钮
        View replyBtnView = ((BaseChatRowViewHolder) holder).replyBtn;
        if (replyBtnView != null) {
            RxViewHelper.getInstance().clicks(replyBtnView, aVoid -> {
                if (onChatItemClickListener != null) {
                    onChatItemClickListener.onReplyClick(data.getFrom());
                }
            });
        }
        // 点击bubble
        View bubbleView = ((BaseChatRowViewHolder) holder).bubble;
        if (bubbleView != null) {
            RxViewHelper.getInstance().clicks(bubbleView, aVoid -> {
                if (onChatItemClickListener != null) {
                    onChatItemClickListener.onBubbleClick(data, holder);
                }
            });
            RxViewHelper.getInstance().longClicks(bubbleView, aVoid -> {
                if (onChatItemClickListener != null) {
                    onChatItemClickListener.onBubbleLongClick(data, bubbleView, (ViewGroup) rootView);
                }
            });
        }
        View avatarView = ((BaseChatRowViewHolder) holder).avatar;
        if (avatarView != null) {
            RxViewHelper.getInstance().clicks(avatarView, aVoid -> {
                if (onChatItemClickListener != null) {
                    onChatItemClickListener.onAvatarClick(data);
                }
            });
        }
    }

    @Override
    public int getItemViewType(int position) {
        final EMMessage message = dataList.get(position);
        if (message == null) {
            return -1;
        }
        int type = ChatCommonUtils.getChatMessageType(message);
        // 文字
        if (type == ChatConstant.MESSAGE_TYPE_TXT) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_TEXT.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_TEXT.ordinal();
        }
        // 图片
        else if (type == ChatConstant.MESSAGE_TYPE_IMAGE) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_IMAGE.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_IMAGE.ordinal();
        }
        // 视频
        else if (type == ChatConstant.MESSAGE_TYPE_VIDEO) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_VIDEO.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_VIDEO.ordinal();
        }
        // 视频通话
        else if (type == ChatConstant.MESSAGE_TYPE_VIDEO_CALL) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_VIDEO_CALL.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_VIDEO_CALL.ordinal();
        }
        // 音频
        else if (type == ChatConstant.MESSAGE_TYPE_VOICE) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_VOICE.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_VOICE.ordinal();
        }
        // 音频通话
        else if (type == ChatConstant.MESSAGE_TYPE_VOICE_CALL) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_VOICE_CALL.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_VOICE_CALL.ordinal();
        }
        // 红包
        else if (type == ChatConstant.MESSAGE_TYPE_RED_PACKAGE) {
            return message.direct() == EMMessage.Direct.RECEIVE ?
                    ITEM_TYPE.ITEM_TYPE_RECEIVE_RED_PACKAGE.ordinal() : ITEM_TYPE.ITEM_TYPE_SEND_RED_PACKAGE.ordinal();
        }
        // 通知类型
        else if (type == ChatConstant.MESSAGE_TYPE_NOTIFY) {
            return ITEM_TYPE.ITEM_NOTIFY_VIEW.ordinal();
        }
        // 默认
        else {
            return ITEM_TYPE.ITEM_DEFAULT_VIEW.ordinal();// invalid
        }
    }

    @Override
    public int getItemCount() {
        return dataList.size();
    }


}
